package crontab

import (
	"github.com/spf13/cast"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	vod "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/vod/v20180717"
	global2 "longmen/server/config/global"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/db/redis/cache"
	"time"
)

const (
	DelDaysAgo = 15
)

// 删除7天前的录制
func DeleteLiveRecord() {
	configPri := cache.GetConfigPri()
	cred := common.NewCredential(configPri.QcloudLiveSecretid, configPri.QcloudLiveSecretkey)
	credential := common.NewCredential(
		cred.SecretId,
		cred.SecretKey,
	)
	cpf := profile.NewClientProfile()
	client, _ := vod.NewClient(credential, "", cpf)
	var fileIds []string
	videos := getExpiredVideo()

	for _, v := range videos {
		req := vod.NewDeleteMediaRequest()
		req.FileId = common.StringPtr(v.TCFileID)
		req.SubAppId = common.Uint64Ptr(cast.ToUint64(configPri.QcloudLiveAppid))
		req.DeleteParts = []*vod.MediaDeleteItem{}
		_, err := client.DeleteMedia(req)
		global2.Log.Debugf("json:%s", req.ToJsonString())
		if err != nil {
			global2.Log.Errorf("DeleteLiveRecrod fileId:%v,err:%v", *req.FileId, err)
			continue
		}
		global2.Log.Debugf("删除点播fileId:%d成功", req.FileId)
		fileIds = append(fileIds, v.TCFileID)
	}
	if len(fileIds) > 0 {
		delExpiredVideo(fileIds)
	}
}

func getExpiredVideo() []*models_main.Video {
	resp := make([]*models_main.Video, 0)
	if err := global2.GetR().Model(&models_main.Video{}).Where("create_time < ? and type = ? and tc_file_id <> ?", time.Now().Unix()-DelDaysAgo*86400, models_main.LiveRecordType, "").Find(&resp).Error; err != nil {
		global2.Log.Debugf("getExpiredVideo err:%v", err)
	}
	return resp
}

func delExpiredVideo(fileIds []string) bool {
	if err := global2.GetX().Where("tc_file_id in ?", fileIds).Delete(&models_main.Video{}).Error; err != nil {
		global2.Log.Debugf("delExpiredVideo err:%v", err)
		return false
	}
	return true
}
